package assists.caches
{
	import flash.display.Bitmap;
	import flash.display.BitmapData;
	import flash.display.Loader;
	import flash.events.Event;
	import flash.filesystem.File;
	import flash.filesystem.FileMode;
	import flash.filesystem.FileStream;
	import flash.net.FileReference;
	import flash.utils.ByteArray;
	
	public class SaveImage
	{
		private var saveCallBack:Function;
		
		public function SaveImage()
		{
		}
		
		private function save(ba:ByteArray,file:File,fileName:String):void
		{
			var _fileRef:File= file;//用于保存文件
			var fs:FileStream = new FileStream();
			try{
				fs.open(_fileRef,FileMode.WRITE);
				fs.writeBytes(ba);
				fs.close();
				ba.clear();
				
				if(saveCallBack is Function){
					saveCallBack(fileName);
				}
			}catch(e:Error){
				trace(e.message);
			}
		}
		
		public function saveJpg(bitmapData:BitmapData,file:File,fileName:String):void
		{
			var _encoder:JPGEncoder=new JPGEncoder(80);//用于编码位图
			var ba:ByteArray=_encoder.encode(bitmapData);//编码成JPG图片，质量为80
			save(ba,file,fileName);
		}
		
		public function savePng(bitmapData:BitmapData,file:File,fileName:String):void
		{
			var _encoder:PNGEncoder=new PNGEncoder();//用于编码位图
			var ba:ByteArray=_encoder.encode(bitmapData);
			save(ba,file,fileName);
		}
		
		public function saveXML(data:ByteArray,file:File,fileName:String):void
		{
			save(data,file,fileName);
		}
		
		public function saveImgWithCallback(bitmapData:BitmapData,file:File,fileName:String,callBack:Function):void
		{
			saveCallBack = callBack;
			
			if(fileName.indexOf("png"))
			{
				this.savePng(bitmapData,file,fileName);
			}else
			{
				this.saveJpg(bitmapData,file,fileName);
			}
		}
	}
}